package com.caiyigo.baihua.fetion;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;

import com.caiyigo.baihua.entity.Xuesheng;

import net.solosky.maplefetion.FetionClient;
import net.solosky.maplefetion.bean.Message;
import net.solosky.maplefetion.event.ActionEvent;
import net.solosky.maplefetion.event.action.ActionEventListener;
import net.solosky.maplefetion.util.StringHelper;

public class SendFetion implements Callable<Result> {
	private static Logger logger = Logger.getLogger(SendFetion.class);
	private FetionClient client;
	private String tel;
	private String msg;
	private Result result = null;
	private Map<String, Xuesheng> xueshengMapKeyAtMobile;

	public SendFetion(FetionClient client, String tel, String msg,
			Map<String, Xuesheng> xueshengMapKeyAtMobile) {
		this.client = client;
		this.tel = tel;
		this.msg = msg;
		this.xueshengMapKeyAtMobile = xueshengMapKeyAtMobile;
	}

	@Override
	public Result call() throws Exception {
		return tel(tel, msg);
	}

	public Result tel(final String tel, String msg) throws InterruptedException {
		long mobile = 0;
		try {
			mobile = Long.parseLong(tel);
		} catch (Exception e) {
			logger.warn(tel+"手机号码出错");
			return new Result(tel, null, xueshengMapKeyAtMobile);
		}
		try {
			this.client.sendChatMessage(mobile,
					new Message(StringHelper.qouteHtmlSpecialChars(msg),
							Message.TYPE_PLAIN), new ActionEventListener() {
						public void fireEevent(ActionEvent event) {
							result = new Result(tel, event,
									xueshengMapKeyAtMobile);
						}
					});
			TimeUnit.SECONDS.sleep(5);
		} catch (Exception e) {
			logger.warn("发送飞信出错",e.getCause());
		}
		return result;

	}

	public void appendNewText(final String txt) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				fetion.taInfo.setText(fetion.taInfo.getText() + txt);
				fetion.taInfo.setCaretPosition(fetion.taInfo.getDocument()
						.getLength());
			}
		});
	}
}
